#include "filetransfer.h"
#include "protocol.h"
#include <QTimer>
#include <QFile>
#include <QProgressDialog>
#include <QDir>
#include <QDateTime>
#include <QDebug>

FileTransferService::FileTransferService(QObject *parent)
    : QObject(parent)
    , protocol(nullptr)
    , processTimer(new QTimer(this))
    , progressTimer(new QTimer(this))
    , nextTransferId(1)
    , progressDialog(nullptr)
{
    // 设置处理定时器
    processTimer->setInterval(100); // 100ms检查一次
    connect(processTimer, &QTimer::timeout, this, &FileTransferService::processNextTransfer);
    
    // 设置进度更新定时器
    progressTimer->setInterval(500); // 500ms更新一次
    connect(progressTimer, &QTimer::timeout, this, &FileTransferService::updateProgress);
    
    // 启动定时器
    processTimer->start();
    progressTimer->start();
}

FileTransferService::~FileTransferService()
{
    cancelAllTransfers();
}

void FileTransferService::setProtocol(Protocol *protocol)
{
    this->protocol = protocol;
}

int FileTransferService::uploadFile(const QString &localPath, const QString &remotePath)
{
    QFileInfo fileInfo(localPath);
    if (!fileInfo.exists()) {
        emit transferFinished(nextTransferId, false, tr("本地文件不存在: %1").arg(localPath));
        return -1;
    }
    
    TransferItem item;
    item.localPath = localPath;
    item.remotePath = remotePath;
    item.size = fileInfo.size();
    item.transferred = 0;
    item.isUpload = true;
    item.id = nextTransferId;
    
    pendingTransfers.enqueue(item);
    
    int transferId = nextTransferId++;
    return transferId;
}

int FileTransferService::downloadFile(const QString &remotePath, const QString &localPath)
{
    TransferItem item;
    item.localPath = localPath;
    item.remotePath = remotePath;
    item.size = 0; // 下载时可能还不知道文件大小
    item.transferred = 0;
    item.isUpload = false;
    item.id = nextTransferId;
    
    pendingTransfers.enqueue(item);
    
    int transferId = nextTransferId++;
    return transferId;
}

void FileTransferService::cancelTransfer(int transferId)
{
    // 检查是否在等待队列中
    for (int i = 0; i < pendingTransfers.size(); ++i) {
        if (pendingTransfers.at(i).id == transferId) {
            pendingTransfers.removeAt(i);
            emit transferCanceled(transferId);
            return;
        }
    }
    
    // 检查是否在活动队列中
    if (activeTransfers.contains(transferId)) {
        cleanupTransfer(transferId);
        emit transferCanceled(transferId);
    }
}

void FileTransferService::cancelAllTransfers()
{
    // 取消所有等待的传输
    while (!pendingTransfers.isEmpty()) {
        TransferItem item = pendingTransfers.dequeue();
        emit transferCanceled(item.id);
    }
    
    // 取消所有活动的传输
    QList<int> activeIds = activeTransfers.keys();
    for (int id : activeIds) {
        cleanupTransfer(id);
        emit transferCanceled(id);
    }
}

QList<TransferItem> FileTransferService::getPendingTransfers() const
{
    QList<TransferItem> transfers;
    for (int i = 0; i < pendingTransfers.size(); ++i) {
        transfers.append(pendingTransfers.at(i));
    }
    return transfers;
}

QList<TransferItem> FileTransferService::getActiveTransfers() const
{
    return activeTransfers.values();
}

void FileTransferService::pauseTransfer(int transferId)
{
    Q_UNUSED(transferId)
    // 暂停传输功能
}

void FileTransferService::resumeTransfer(int transferId)
{
    Q_UNUSED(transferId)
    // 恢复传输功能
}

void FileTransferService::processNextTransfer()
{
    if (pendingTransfers.isEmpty() || !protocol)
        return;
        
    // 检查是否可以开始新的传输（例如限制并发数）
    if (activeTransfers.size() >= 64) // 限制同时传输数
        return;
        
    TransferItem item = pendingTransfers.dequeue();
    activeTransfers.insert(item.id, item);
    emit transferStarted(item.id);
    
    startTransfer(item);
}

void FileTransferService::onTransferDataReceived(const QByteArray &data)
{
    Q_UNUSED(data)
    // 处理接收到的传输数据
}

void FileTransferService::onTransferCompleted(int transferId, bool success, const QString &error)
{
    Q_UNUSED(transferId)
    Q_UNUSED(success)
    Q_UNUSED(error)
    // 处理传输完成事件
}

void FileTransferService::updateProgress()
{
    // 更新传输进度
    QList<int> activeIds = activeTransfers.keys();
    for (int id : activeIds) {
        TransferItem &item = activeTransfers[id];
        emit transferProgress(id, item.transferred, item.size);
    }
}

void FileTransferService::startTransfer(TransferItem &item)
{
    Q_UNUSED(item)
    // 开始文件传输
    if (item.isUpload) {
        // 开始上传文件
        QFile *file = new QFile(item.localPath);
        if (file->open(QIODevice::ReadOnly)) {
            transferFiles.insert(item.id, file);
            // 在实际实现中，这里会开始读取文件并发送数据
        } else {
            emit transferFinished(item.id, false, tr("无法打开文件进行读取: %1").arg(item.localPath));
            cleanupTransfer(item.id);
        }
    } else {
        // 开始下载文件
        QFile *file = new QFile(item.localPath);
        if (file->open(QIODevice::WriteOnly)) {
            transferFiles.insert(item.id, file);
            // 在实际实现中，这里会请求远程开始发送文件数据
        } else {
            emit transferFinished(item.id, false, tr("无法打开文件进行写入: %1").arg(item.localPath));
            cleanupTransfer(item.id);
        }
    }
}

void FileTransferService::cleanupTransfer(int transferId)
{
    // 清理传输资源
    activeTransfers.remove(transferId);
    
    if (transferFiles.contains(transferId)) {
        QFile *file = transferFiles.take(transferId);
        file->close();
        delete file;
    }
}